#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* reads the stdio to buffer and making sure no overflow occurs */
int readBuffer(char *buff,int size){
	int c = 0;
	int i = 0;
	while (((c = getchar()) != '\n') && (i< (size-1) )) {
		*(buff + i++) = c;
	}
	*(buff + i++) = '\0';
	if (i==size)
		return 0; /* buff overflow */
	return 1;
}

int getParentPath(char *path){
	char *ptr = NULL;
	
	ptr = path;
	while (*ptr != '\0'){
		ptr++;
	}
	ptr--;
	if (*ptr == '/') return 0;
	
	ptr--;
	while (*ptr != '/')
		ptr--;
	*ptr = '\0';	
	return 1;
}
int main()
{
	char Buffer[200];
	char* path=NULL;
	InBuffer[0] = '\0';

	while (strcmp(Buffer,"QUIT") != 0){
		printf("MYSHELL>> ");
		if (readBuffer(Buffer,200) == 0){
			printf("Command is too long. 200 char max.\n");
			continue;
		}

		if (strcmp(Buffer,"DIR"){
			system("ls -l");
			continue;
		}
		if (strcmp(Buffer,"CD"){
			continue;
		}
		if (strcmp(Buffer,"CD .."){
			path = getcwd(NULL);
			getParentPath(path);
			chdir(path);
			free(path);			
			continue;
		}
		/* else exec */
		system(Buffer);
		printf('\n');
		
	}
	return 0;
}


